import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gesture_zoom_box/gesture_zoom_box.dart';
import 'package:handwritingprocessing/handwritingprocessing.dart';
import 'package:image/image.dart' as gimage;

const blackWriteVals = [1000, 5, 11, 19, 30, 42, 55];
const removalRedVals = [5, 0, 9, 13, 25, 36, 50];
const removalBlueVals = [3, 0, 9, 19, 25, 36, 50];

class FillColorPage extends StatefulWidget {
  @override
  FillColorPageState createState() => new FillColorPageState();
}

class FillColorPageState extends State<FillColorPage> {
  List<String> _urls = [];
  List<ui.Image> _uiImages = [];
  List<Image> _imgs = [];
  List<Image> _newImgs = [];

  double minh = 100;
  double maxh = 124;
  double mins = 43;
  double maxs = 255;
  double minv = 46;
  double maxv = 255;

  var key = GlobalKey();

  var _controller = TextEditingController();

  Uint8List _byteData;
  int _blackWriteIndex = 0;
  int _removalRedIndex = 0;
  int _removalBlueIndex = 0;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: GestureZoomBox(
          maxScale: 10.0,
          doubleTapScale: 3.0,
          duration: Duration(milliseconds: 200),
          child: Column(children: <Widget>[
            TextField(controller: _controller),
            RaisedButton(
              child: Text('添加'),
              onPressed: () async {
                _loadImgs(_controller.text);
              },
            ),
            Expanded(
              child: ListView.separated(
                  itemBuilder: (context, index) {
                    return Column(
                      children: <Widget>[
                        if (_imgs[index] != null) _imgs[index],
                        if (_newImgs[index] != null) _newImgs[index],
                      ],
                    );
                  },
                  separatorBuilder: (context, index) {
                    return Divider(
                      thickness: 10,
                      color: Colors.black,
                    );
                  },
                  itemCount: _newImgs.length),
            ),
          ])),
      floatingActionButton: ButtonBar(
        children: <Widget>[
          RaisedButton(
            child: Text('黑白'),
            onPressed: () async {
              _blackWriteIndex = await _simpleDialog();
              print('_$_blackWriteIndex');
              for (int i = 0; i < _imgs.length; i++) {
                await _loadImage(_imgs[i], i, 7);
              }
//              ByteData first = await rootBundle.load('assets/images/cup.jpg');
//              ByteData second = await rootBundle.load('assets/images/cup2.jpg');
//              var val =
//                  await Handwritingprocessing.handwriting(_byteData, 0);
//              showDialog<void>(
//                context: context,
//                barrierDismissible: true,
//                // false = user must tap button, true = tap outside dialog
//                builder: (BuildContext dialogContext) {
//                  return AlertDialog(
//                    title: Text('$val'),
//                    content: Text('dialogBody'),
//                    actions: <Widget>[
//                      FlatButton(
//                        child: Text('buttonText'),
//                        onPressed: () {
//                          Navigator.of(dialogContext)
//                              .pop(); // Dismiss alert dialog
//                        },
//                      ),
//                    ],
//                  );
//                },
//              );
            },
          ),
          RaisedButton(
            child: Text('去红'),
            onPressed: () async {
              _removalRedIndex = await _simpleDialog();
              for (int i = 0; i < _imgs.length; i++) {
                await _loadImage(_imgs[i], i, 2);
              }
            },
          ),
          RaisedButton(
            child: Text('去蓝'),
            onPressed: () async {
              _removalBlueIndex = await _simpleDialog();
              for (int i = 0; i < _imgs.length; i++) {
                await _loadImage(_imgs[i], i, 4);
              }
            },
          )
        ],
      ),

//      bottomNavigationBar: Column(
//        mainAxisSize: MainAxisSize.min,
//        children: <Widget>[
//          getRangeSlider(
//              max: 180,
//              rangeSlideMin: minh,
//              rangeSlideMax: maxh,
//              rangeSlideChange: (min, max) {
//                setState(() {
//                  minh = min;
//                  maxh = max;
//                });
//              }),
//          getRangeSlider(
//              rangeSlideMin: mins,
//              rangeSlideMax: maxs,
//              rangeSlideChange: (min, max) {
//                setState(() {
//                  mins = min;
//                  maxs = max;
//                });
//              }),
//          getRangeSlider(
//              rangeSlideMin: minv,
//              rangeSlideMax: maxv,
//              rangeSlideChange: (min, max) {
//                setState(() {
//                  minv = min;
//                  maxv = max;
//                });
//              }),
//        ],
//      ),
    );
  }

  Future<int> _simpleDialog() async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(
            title: Text('选择内容'),
            children: <Widget>[
              for (int i = 0; i < blackWriteTitle.length; i++)
                _buildDialogOption(i),
            ],
          );
        });
    return result;
  }

  Column _buildDialogOption(int index) {
    return Column(
      children: <Widget>[
        SimpleDialogOption(
          child: Text(blackWriteTitle[index]),
          onPressed: () {
            Navigator.pop(context, index);
          },
        ),
        Divider(),
      ],
    );
  }

  Widget getRangeSlider(
      {double max = 255,
      double rangeSlideMin = 0,
      double rangeSlideMax = 10,
      Function(double, double) rangeSlideChange}) {
    return SliderTheme(
      //样式的设计
      data: SliderThemeData(
        inactiveTickMarkColor: Colors.red,
        inactiveTrackColor: Colors.yellow,
      ),
      child: RangeSlider(
        //滑动时上方的提示标签
        labels: RangeLabels("$rangeSlideMin", "$rangeSlideMax"),
        //当前Widget滑块的值
        values: RangeValues(rangeSlideMin, rangeSlideMax),
        //最小值
        min: 0,
        //最大值
        max: max,
        //最小滑动单位值
        divisions: 100,
        //未滑动的颜色
        inactiveColor: Colors.grey,
        //活动的颜色
        activeColor: Colors.blue,
        //滑动事件
        onChanged: (RangeValues values) {
          //滑动时更新widget的状态值
          rangeSlideChange(values.start, values.end);
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _loadImgs(null);
    setState(() {});
  }

  void _loadImgs(String url) async {
    if (url != null) {
      _urls = [url];
    } else {
      _urls = [
        "https://qiniu.culink.cn/WechatIMG48.jpg",
        "http://d.121tongbu.com:59880/zentao/file-read-161.png",
        "http://d.121tongbu.com:59880/zentao/file-read-159.png",
        "http://d.121tongbu.com:59880/zentao/file-read-157.png",
        "http://d.121tongbu.com:59880/zentao/file-read-141.png"
      ];
    }
    _imgs = List(_urls.length);
    _newImgs = List(_urls.length);
    for (int i = 0; i < _imgs.length; i++) {
//      File file = await DefaultCacheManager().getSingleFile(_urls[i]);
      _imgs[i] = Image.network(_urls[i]);
      await _loadImage(_imgs[i], i, 0);
    }
  }

  Future _loadImage(Image image, int index, int minh) async {
    image.image
        .resolve(new ImageConfiguration())
        .addListener(new ImageStreamListener(
      (ImageInfo info, bool _) async {
        var pixelsData =
            await info.image.toByteData(format: ui.ImageByteFormat.png);
        Uint8List byteData = pixelsData.buffer.asUint8List();
        _byteData = byteData;
//        for (int i = 0; i < byteData.length; i += 4) {
//          var rg = byteData[i] - byteData[i + 1] > 25;
//          var rb = byteData[i] - byteData[i + 2] > 25;
//          var br = byteData[i + 2] - byteData[i] > 10;
//          var bg = byteData[i + 2] - byteData[i + 1] > 10;
//          if (rg && rb) {
//            byteData[i + 1] = byteData[i];
//            byteData[i + 2] = byteData[i];
//          }
//          if (br && bg) {
//            byteData[i] = byteData[i + 2];
//            byteData[i + 1] = byteData[i + 2];
////            byteData[i+2]=255;
//          }
//        }

        byteData = await Handwritingprocessing.handwriting(byteData, minh,
            blackWriteVal: blackWriteVals[_blackWriteIndex],
            removalRedVal: removalRedVals[_removalRedIndex],
            removalBlueVal: removalBlueVals[_removalBlueIndex],
            patchSize: 6);

//        byteData = await Opencvplugin.adaptiveThreshold(
//            byteData,
//            0xFF,
//            OpencvConst.adaptiveThreshGaussianC,
//            OpencvConst.threshBinary,
//            9,
//            11);

        _newImgs[index] = (Image.memory(byteData));
        setState(() {});
        return byteData;
      },
    ));

//    double minh=150;
//    double maxh=180;
//    double mins=150;
//    double maxs=255;
//    double minv=150;
//    double maxv=255;
//    byteData = await Opencvplugin.inRange(
//        byteData, minh, mins, minv, maxh, maxs, maxv);

//    byteData =
//        await ImgProc.morphologyEx(byteData, ImgProc.morphClose, [1, 1]);
//    byteData =
//        await ImgProc.morphologyEx(byteData, ImgProc.morphOpen, [1, 1]);

//    byteData = await Opencvplugin.adaptiveThreshold(byteData, 0xFF,
//        OpencvConst.adaptiveThreshGaussianC, OpencvConst.threshBinary, 9, 11);
  }

  @override
  void dispose() {
    super.dispose();
  }
}

class GImageUtils {
  static Future<gimage.Image> fromUiImage(ui.Image img) async {
    //必须转成rawRgba，不然转码很浪费时间
    var pixelsData = await img.toByteData(format: ui.ImageByteFormat.rawRgba);
    var pixels = pixelsData.buffer.asUint8List();
    var width = img.width;
    var height = img.height;
    //得到im对象
    gimage.Image im = gimage.Image.fromBytes(width, height, pixels);
    return im;
  }

  static List<int> toUiImage(gimage.Image gsImage) {
    // 这里有个问题，你要把gsImage显示在屏幕上，必须给它转码，Image小部件是不支持rgba格式的。
    // 转JPG格式
    var jpgImage = gimage.encodeJpg(gsImage, quality: 80);
    return jpgImage;
  }
}
